package sng.net.http
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;
	
	import sng.net.http.cspkg.TWebPkg;

	/**
	 * Http发送消息进程 
	 * @author leonliu
	 * 
	 */	
	public class SendThread
	{
		/**
		 * url加载 
		 */		
		private var _loader:URLLoader;
		
		/**
		 * 此进程是否在被使用
		 */		
		private var _usable:Boolean;
		
		/**
		 * 
		 */		
		private var _onRecv:Function;
		
		
		public function SendThread()
		{
			_loader = new URLLoader();
			
			_usable = true;
			
			//
			initLoader();
			
		}
		
		private function initLoader():void
		{
			_loader.dataFormat = URLLoaderDataFormat.BINARY;
			_loader.addEventListener(Event.COMPLETE, onComplete);
			_loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
		}
		
		public function get usable():Boolean
		{
			return _usable;
		}
		
		/**
		 * 发送请求 
		 * @param urlReq
		 * @param onRecv
		 * @return 
		 * 
		 */		
		public function sendReq(urlReq:URLRequest, onRecv:Function):void
		{
			_onRecv = onRecv;
			var tw:TWebPkg=new TWebPkg();
//			tw.decode(ByteArray(urlReq.data));
			var ba:ByteArray =ByteArray(urlReq.data);
			ba.position=0;
			var ret:int = tw.decode(ba);
	
			
			_loader.load(urlReq);
			
			_usable = false;
		}
		
		/**
		 * 接收数据 
		 * @param event
		 * 
		 */		
		private function onComplete(event:Event):void
		{
			_usable = true;
			
			try
			{
				// buf
				var recvBuf:ByteArray = event.currentTarget.data as ByteArray;
				
				if(!recvBuf)
				{
					trace("http recv data is null");
				}
				
				_onRecv(recvBuf);
				
			}
			catch (err:Error)
			{
				trace("ERROR:" + err.getStackTrace());
			}
			
		}  
		
		
		private function onIOError(event:Event):void
		{
			_usable = true;
			
			trace("http proxy onIOError"+event.toString());
			
		}
		
		
		private function removeEvents(event:Event):void
		{
			if(event.target is URLLoader)
			{
				event.target.removeEventListener(Event.COMPLETE, onComplete);
				event.target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			}
			
		}
	}
}